"use client";

import { type ReactNode, createContext, useRef, useContext } from "react";
import { useStoreWithEqualityFn } from "zustand/traditional";
import { createCommonStore, State, Store } from "../stores";

export type StoreApi = ReturnType<typeof createCommonStore>;

export const StoreContext = createContext<StoreApi | undefined>(undefined);

export interface CommonStoreProviderProps {
  children: ReactNode;
  data: State;
}

export const CommonStoreProvider = ({
  children,
  data,
}: CommonStoreProviderProps) => {
  const storeRef = useRef<StoreApi>();
  if (!storeRef.current) {
    storeRef.current = createCommonStore({ ...data });
  }

  return (
    <StoreContext.Provider value={storeRef.current}>
      {children}
    </StoreContext.Provider>
  );
};

export const useCommonStore = <T,>(
  selector: (store: Store) => T,
  equalityFn?: (a: T, b: T) => boolean
): T => {
  const commonStoreContext = useContext(StoreContext);

  if (!commonStoreContext) {
    throw new Error(`useCounterStore must be used within CounterStoreProvider`);
  }

  return useStoreWithEqualityFn(commonStoreContext, selector, equalityFn);
};
